package com.controller;

import com.alibaba.fastjson.JSONObject;
import com.entity.base.Result;
import com.entity.down_ret;
import com.service.oss.ShareService;
import com.service.oss.OSSClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

@RestController
@RequestMapping("/api/share")
@Api(tags = "链接分享接口", description = "提供相关的 Rest API")
public class ShareController {
    @Autowired
    private ShareService shareService;

    @PostMapping("/addShare")
    @ApiOperation("创建分享链接")
    public Result addShare(@RequestBody JSONObject jsonObject, HttpServletRequest req) {
        String username = jsonObject.get("username").toString();
        String filePath = jsonObject.get("filePath").toString();
        boolean isEncrypt = jsonObject.get("pwd").toString().equals("0");//pwd为0即加密
        return shareService.addShare(username, new Date(), filePath, isEncrypt);

    }

    @PostMapping("/getShare")
    @ApiOperation("使用分享链接")
    public Result getShare(@RequestBody JSONObject jsonObject, HttpServletResponse res) throws IOException, ParseException {
        String number = jsonObject.get("number").toString();
        String pwd = jsonObject.get("pwd").toString();
        String path = shareService.getShare(number, pwd);
        if (path.equals("0")) {
            return Result.error("秘钥或提取码错误!");
        }

        down_ret down = new OSSClient().previewFile(path);
        return Result.success(down);
    }

    @PostMapping("/getStoreHouse")
    @ApiOperation("使用分享链接")
    public Result getStoreHouse(@RequestBody JSONObject jsonObject, HttpServletResponse res) throws IOException, ParseException {
        String number = jsonObject.get("number").toString();
        String pwd = jsonObject.get("pwd").toString();
        String path = shareService.getShare(number, pwd);
        if (path.equals("0")) {
            return Result.error("秘钥或提取码错误!");
        }

        return Result.success(path);
    }

    @ApiOperation("获得当前服务器所有分享列表")
    @GetMapping("/getShareList")
    public Result getShareList(){
       return Result.success(shareService.getShareList());
    }

    @ApiOperation("获得指定用户分享的文件列表")
    @PostMapping("/getShareMeList")
    public Result getShareMeList(@RequestBody JSONObject jsonObject){
        String name = jsonObject.get("username").toString();
        return Result.success(shareService.getShareMeList(name));
    }









}
